package com.csx.orm.mybatis.mapper.provider;

import com.csx.orm.mybatis.entity.User;
import org.apache.ibatis.jdbc.SQL;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2023/11/18 周六 13:57
 */
public class UserMapperProvider {

    /**
     * 1. 带有查询条件的sql拼接逻辑
     */
    public String findConditionSelectProvider(User condition) {
        SQL sql = new SQL();
        sql.SELECT("*").FROM("user");
        if(condition.getId() != null) {
            sql.AND().WHERE("id = #{id}");
        }
        if (condition.getFirstName() != null && condition.getFirstName().trim().length() > 0) {
            sql.AND().WHERE("first_name like concat('%', #{firstName}, '%')");
        }
        sql.ORDER_BY("id asc");
        return sql.toString();
    }

    /**
     * 2. 使用 VALUES 方法拼接多个条件
     */
    public String saveInsertProvider(User user) {
        SQL sql = new SQL();
        sql.INSERT_INTO("user");
        sql.VALUES("id", "#{id}");
        sql.VALUES("first_name", "#{firstName}");
        sql.VALUES("last_name", "#{lastName}");
        sql.VALUES("age", "#{age}");
        sql.VALUES("city", "#{city}");
        return sql.toString();
    }

    /**
     * 3. 通过 INTO_COLUMNS 方法向里面插入批量数据
     */
    public String saveInsertProviderColumns(User user) {
        SQL sql = new SQL();
        sql.INSERT_INTO("user");
        sql.INTO_COLUMNS("id", "first_name", "last_name", "age", "city")
                .INTO_VALUES("#{id}", "#{firstName}", "#{lastName}", "#{age}", "#{city}");
        return sql.toString();
    }

    /**
     * 4. 修改数据
     */
    public String updateUpdateProvider(User user) {
        SQL sql = new SQL();
        sql.UPDATE("user");
        if(user.getFirstName() != null && user.getFirstName().trim().length() > 0) {
            sql.SET("first_name = #{firstName}");
        }
        if(user.getLastName() != null && user.getLastName().trim().length() > 0) {
            sql.SET("last_name = #{lastName}");
        }
        sql.WHERE("id = #{id}");
        return sql.toString();
    }

    /**
     * 5. 删除数据
     */
    public String deleteDeleteProvider(Long id) {
        SQL sql = new SQL();
        sql.DELETE_FROM("user");
        sql.WHERE("id = #{id}");
        return sql.toString();
    }
}
